<?php


namespace app\index\controller;
use app\common\Timer;
use app\common\validate\User;
use app\index\model\Member as MemberModel;
use think\Controller;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\facade\Log;

class Member extends Controller
{

    /*------注册基本逻辑和验证------*/
    public function registerThisInBase($data){
        try {
            if(!null == MemberModel::where("member_email", $data["member_email"])->find() ||(strlen($data["member_email"])===0) )
            {return "3";}
        } catch (DataNotFoundException $e) {
        } catch (ModelNotFoundException $e) {
        } catch (DbException $e) {
            /*抛出异常*/
            return "2";
        }
        try {
            if(!null == MemberModel::where("member_name", $data["member_name"])->find()){
                return "4";
            }
        } catch (DataNotFoundException $e) {
        } catch (ModelNotFoundException $e) {
        } catch (DbException $e) {
            /*抛出异常*/
            return "2";
        }
        if($data["member_name"] === "admin"){
            return "4";
        }
            $member = new Member();
            return $member->registerInsert($data);
    }

    /*----注册插入数据-----*/
    public function registerInsert($data){
        $validata = new User();
        if(null == $validata->check($data)) {
            $member = new MemberModel();
            $time = new Timer();
            if($member->save([
                "member_email" => $data['member_email'],
                "member_name" => $data['member_name'],
                "member_join_stamp" => $time->getTime(),
                "member_password" => md5($data['member_password']),
            ])){
                return "1";
            };
        }
        return "2";
    }


// TODO OK
    /*-----查询语句------*/
    public function registerCheckName(){
        if ($this->request->isAjax()){
            $nickname = $this->request->get("nickname");
            try {
                /*-----名字不可用-----*/
                if(strlen($nickname)<=3 || strlen($nickname) >= 20){
                    return false;
                }else{
                    MemberModel::where("member_name", $nickname)->selectOrFail();
                    return false;
                }
            } catch (DataNotFoundException $e) {
            } catch (ModelNotFoundException $e) {
            } catch (DbException $e) {
                Log::warning( "出现异常");
            }
            if($nickname === "admin"){
                return false;
            }
           return true;
        }
        return false;
        }



}